import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import { WeaColorPicker, WeaTab, WeaLeftRightLayout, WeaTableEditable, WeaRightMenu, WeaDialog, WeaTools, WeaErrorPage, WeaLocaleProvider, WeaInput,WeaMoreButton } from 'ecCom';
import { Popover, Button, Checkbox, Input, message,Modal } from 'antd';
import './followDilog.less';
import FollowTypeSetting from "./FollowTypeSetting"
const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;
@observer
class TagTypeSelectDialog extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tagData: null,
            addInputShow: true,
            visible: false,
            hoverOut: true,
            inputValue: '',
        }
    }
    componentWillMount() {
    }
    componentWillReceiveProps(nextProps) {
        const {data} = this.props
        this.setState({ visible: nextProps.visible })
    }

    componentDidMount() {
        const{followTypeSettingStore}=this.props;
        const{getWorkflowAttentionTypeSet}=followTypeSettingStore;
        getWorkflowAttentionTypeSet()
    }

    componentWillUpdate = (nextProps) => {
        const{followTypeSettingStore, visible, FollowRequestid}=nextProps;
        const{getWorkflowAttentionTypeSet}=followTypeSettingStore;
        if(this.props.visible==false&&visible==true){
            getWorkflowAttentionTypeSet(FollowRequestid);
        }
    }

    openSettingDialog = () => {
        const{followTypeSettingStore}=this.props;
        const{setState, getAttentionTypeSet}=followTypeSettingStore;
        setState({showDialog:true,openType:""});
        getAttentionTypeSet('refresh')
    }
    onChange = (id, e) => {
        const{tagList}=this.props.followTypeSettingStore;
        let newdata = tagList.get("datas")||[];
        newdata.map((val) => {
            if (val.id == id) {
                val.checked = e.target.checked
            }
        })
        tagList.set("datas",newdata)
    }
    // addInputShow = () => {
    //     this.setState({ addInputShow: true })
    // }
    onVisibleChange = (data) => {
        if (data == false) {
            this.setState({ visible: false })
            this.props.onVisibleChange(false)
        }
    }
    batchcacelAll = () =>{
        const{followTypeSettingStore,makeSureCallBack, FollowRequestid}=this.props;
        const{saveAttention, tagList,batchdelAll}=followTypeSettingStore;
        let newdata = tagList.get("datas")||[];
        newdata.map((val) => {
            val.checked = false
        })
        tagList.set("datas",newdata)
        batchdelAll({src:"delByRequestids",requestids:FollowRequestid},"",makeSureCallBack);
        this.submit();
      }
    cancelAll = () => {
        const{tagList}=this.props.followTypeSettingStore;
        let newdata = tagList.get("datas")||[];
        newdata.map((val) => {
            val.checked = false
        })
        tagList.set("datas",newdata)
        this.submit()
    }
    DocancelAll = () =>{
        let _this=this;
        if(this.props.isSingle){
            confirm({
            title: getLabel('131329','信息确认'),
            content: getLabel('511455','确定要清除该流程的所有关注类型吗？'),
            okText: getLabel(826,'确定'),
            onOk() {
                _this.cancelAll();
            },
            onCancel() {},
          }); 
        }else{
            confirm({
                title: getLabel('131329','信息确认'),
                content: getLabel('511454','确定要清除选中流程的所有关注类型吗？'),
                okText: getLabel(826,'确定'),
                onOk() {
                    _this.batchcacelAll();
                },
                onCancel() {},
              });   
        }  
      }
    same = () =>{
        const{tagList}=this.props.followTypeSettingStore;
        const arr =tagList.get("datas").map((val,index)=>{
            if(val.showname==String(this.state.inputValue).trim()){
                return false
            }else{
                return true
            }
        })
        return arr.indexOf(false) 
    }
    addSure = () => {
        const{addBtn}=this.props;
        const{tagList}=this.props.followTypeSettingStore;
        if (String(this.state.inputValue).trim() == ""||this.same()!=-1) {
            String(this.state.inputValue).trim() == "" ? message.warning(getLabel('511461','关注类型名称不能为空')) : message.warning(getLabel('511462','该关注类型已存在'));
            return
        }
        this.setState({ inputValue: '', hoverOut: true })
        addBtn(this.state.inputValue)
    }
    handle = (e) => {
        this.setState({ inputValue: e })
    }
    getFontColor=(value) =>{
        let red = parseInt(value.substring(1,3),16)
        let green = parseInt(value.substring(3,5),16)
        let blue = parseInt(value.substring(5,7),16)
        let res = red*0.299 + green*0.587 + blue*0.114
        if (res>186){
            return "#000000"
        }else{
            return "#ffffff"
        }
    }
    submit = () => {
        //将reqid维护到组件的store
        //这里可以换成组件的store
        const{followTypeSettingStore,makeSureCallBack, FollowRequestid}=this.props;
        const{saveAttention, tagList}=followTypeSettingStore;
        let newdata = tagList.get("datas")||[];
        let isSingle = this.props.isSingle
        let ids = ''
        newdata.map((val) => {
            if (val.checked === 'true' || val.checked === true) {
                ids += val.id + ","
            }
        })
        saveAttention({ src: isSingle?'add':FollowRequestid.split(",").length==1?'add':'batchadd', requestids: FollowRequestid, ids },"",makeSureCallBack)
    }
    getList = () => {
        const{ tagList}=followTypeSettingStore;
        let items = []
        let list = tagList.get("datas")||[];
        try{
            list.map((val) => {
                items.push(
                    <div className="tag_dialog">
                        <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@bqj3rt@${val.id}`} className="tags_checkbox"  checked={val.checked == 'false' ? false : val.checked == false ? false : true}
                            onChange={this.onChange.bind(this, val.id)}
                        >
                            <div className="tags_showColor" title={val.showname} style={{ background: val.colorval,color:this.getFontColor(val.colorval) }}>{val.showname}</div>
                        </Checkbox></div>)
            })
            let content =
                <div className="tag_dialog_scope">
                    <div>{items}</div>
                    <div className="add_row">
                        <div className="tag_add_div">
                            {this.state.addInputShow ? <div>
                                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@dqvka8`}
                                placeholder={getLabel('511578','请输入关注类型名称')}
                                inputType={"multilang"}
                                viewAttr="3"
                                isBase64={true}
                                style={{ width: '80%' ,marginTop:"10px",display:"inline-block"}} size="large" value={this.state.inputValue} onChange={this.handle} />
                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8o9e26`} type="primary" onClick={() => { this.addSure() }} style={{position:"relative",left:"40px",top:"-30px",float:"right"}}>{getLabel('611','添加')}</Button>
                                {/* <Button style={{display:"inline-block"}} onClick={() => { this.setState({addInputShow:false}) }}>{getLabel(201, '取消')}</Button> */}
                                </div> :<div className="tag_add_dialog" onClick={this.addInputShow}>{"+"}<span>{getLabel('511445','添加关注类型')}</span></div>}
                        </div>
                    </div>
                </div>
            return content
        }catch(err){
            console.log(err)
        }   
    }
    
    render() {
        const{followTypeSettingStore,visible}=this.props;
        const{tagList,showDialog}=followTypeSettingStore; 
        let title=tagList.get("title")||getLabel('511456','选择关注类型');
        const menu = [
            {
                key: "0",
                icon: <i className="icon-coms-Preservation" />,
                content: getLabel(826,'确定'),
                onClick: () => this.submit()
              },
            {
                key: "1",
                icon: <i className="icon-coms-go-back" />,
                content: getLabel(511458,'取消关注'),
                onClick: () => this.DocancelAll()
              },
             
          ];
        return (
            <div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hrdvqh`}
                    className={"select_type_dailog"}
                    onCancel={() => {this.setState({ visible: false });this.props.cancelCallBack()}}
                    visible={visible}
                    // visible={this.state.visible}
                    style={{ width: 640, height: 301 }}
                    icon="icon-coms-workflow"
                    iconBgcolor="#0079DE"
                    hasScroll
                    title={<div><span dangerouslySetInnerHTML={{__html: title}}></span><span style={{position: 'absolute',right: '-20px'}} 
                    onClick={this.openSettingDialog}><i className="icon-coms-Flow-setting" title={getLabel('507530','设置')} style={{cursor:'pointer'}}></i></span></div>}
                    buttons={[
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9v8wod@btn1`} type="primary" onClick={() => { this.setState({ inputValue: '', hoverOut: true, visible: false },()=>{this.submit();}); }}>{getLabel('826','确定')}</Button>,
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@n7xh14@btn2`} type="primary" onClick={this.DocancelAll}>{getLabel('511458','取消关注')}</Button>,
                    <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@5hp2ir@btn3`} datas={menu} collectParams={{ favouritetype: 2, objid: 0, importantlevel: 1, }} />]}
                >
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@4v5fcm`} datas={menu} collectParams={{ favouritetype: 2, objid: 0, importantlevel: 1, }} style={{overflow:"hidden"}} >
                    {visible&&this.getList()}
                    {/* {this.state.visible&&this.getList()} */}
                    </WeaRightMenu>
                </WeaDialog>
                {showDialog && <FollowTypeSetting ecId={`${this && this.props && this.props.ecId || ''}_FollowTypeSetting@qcg1q0`} followTypeSettingStore={followTypeSettingStore} refresh={this.props.refresh} makeSureCallBack={this.props.makeSureCallBack} ></FollowTypeSetting>}
            </div>
        )
    }

}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@gdreaq`} msg={props.error ? props.error : getLabel(383324, ' 对不起，该页面异常，请联系管理员 ') + '！'} />,
    { error: "" }
)(TagTypeSelectDialog);